{% extends 'index.html' %}
{% block ace-content %}
<!-- ACE Editor -->   
<script src="http://cdn.bootcss.com/ace/1.2.4/ace.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/ext-language_tools.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/ext-old_ie.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/theme-monokai.js"></script> 
<script type="text/javascript" src="/static/dist/js/bootstrap-notify.js"></script>
<style type="text/css">
	#compile-editor {
		/* position: absolute; */
	width: 100%;
	height: 400px;
   }	
</style>
{% endblock %}
{% block page-content %}
<div id="page-wrapper">
    <div class="row">
         <div class="col-lg-12">
              <h1 class="page-header"><i class="fa fa-gears"></i><code>Ansible</code>脚本管理</h1>
         </div>
                <!-- /.col-lg-12 -->
    </div>
	<div class="row">
                <div class="col-lg-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">
 						<i class="fa    fa-gears"></i>脚本执行
                        </div>
                        <div class="panel-body">
                            <div class="row">
                                <div class="col-lg-5">
                                <legend><i class="fa  fa-paper-plane"></i>Ansible服务器</legend>
                                    <form  method="post" id="ansibleModelRun">  {% csrf_token %}
                                        <div class="form-group">
                                            <label>脚本名称</label>
                                            <input class="form-control" name="script_name" id="script_name" value="{{script.script_name}}" disabled>
                                            <p class="help-block">例如：系统检查</p>
                                        </div>  
										<div class="form-group" >			 		             
											<label >动态主机</label>	
											<select class="form-control" name="server_model" id="server_model" onchange="javascript:oBtAnsibleServerl();">
												<option name="server_model" value="" >请选择一个类型</option>
												{% if script.script_type == 'service' %}
													<option value="service" selected="selected" name="server_model">产品线类型</option>
													<option value="group" name="server_model">使用部门</option>
													<option value="custom" name="server_model">自定义</option> 													
												{% elif script.script_type == 'group' %}
													<option value="service" name="server_model">产品线类型</option>
													<option value="group" name="server_model" selected="selected">使用部门</option>
													<option value="custom" name="server_model">自定义</option> 
												{% elif script.script_type == 'custom' %}
													<option value="service" name="server_model">产品线类型</option>
													<option value="group" name="server_model">使用部门</option>
													<option value="custom" name="server_model" selected="selected">自定义</option> 
												{% else %}
													<option value="service" name="server_model">产品线类型</option>
													<option value="group" name="server_model">使用部门</option>
													<option value="custom" name="server_model">自定义</option> 													
												{% endif %}	
													
											</select>		
										</div>
										<div id='project_server'  {% if script.script_type != 'service' %}style="display:none;"{% endif %}>
											<div class="form-group">
												 <label>所属产品线</label>
		                                            <select class="form-control" name="ansible_project"  id="ansible_project" onchange="javascript:oBtProjectSelect();" required>
		                                            	<option name="project" value="" >请选择一个产品线</option>
		                                            	{% for ds in projectList %}
		                                            		{% if ds.id == project.id %}
		                                            			<option name="project" value="{{ds.id}}" selected="selected">{{ds.project_name}}</option>
		                                            		{% else %}
		                                            			<option name="project" value="{{ds.id}}">{{ds.project_name}}</option>
		                                            		{% endif %}
		                                            	{% endfor %}
		                                            </select>
											</div>										
											<div class="form-group">
												 <label>业务类型</label>
			                                    <select class="form-control" name="ansible_service"  id="ansible_service"  onchange="javascript:oBtServiceSelect('service','ansible_service');" required>
			                                    	
			                                         {% for ds in serviceList %}
			                                         	{% if script.script_service == ds.id %}
			                                         		<option name="service" value="{{ds.id}}" selected="selected">{{ds.service_name}}</option>
			                                         	{% else %}
			                                            	<option name="service" value="{{ds.id}}">{{ds.service_name}}</option>
			                                            {% endif %}
			                                         {% endfor %}
			                                    </select>
											</div>	
										</div>																						
										<div id="group_server" class="form-group" {% if script.script_type != 'group' %}style="display:none;"{% else %}style="display:"";"{% endif %}>
											<label>使用部门</label>
		                                    <select class="form-control" name="script_auth_group"  id="script_auth_group" onchange="javascript:oBtServiceSelect('group','script_auth_group');" required>
		                                    		<option name="script_auth_group" value="0" selected="selected">请选择使用组</option>
		                                           {% for ds in groupList %}
		                                         	{% if script.script_group == ds.id %}
		                                         		<option name="group" value="{{ds.id}}" selected="selected">{{ds.name}}</option>
		                                         	{% else %}                              	
		                                            	<option name="group" value="{{ds.id}}">{{ds.name}}</option>
		                                            {% endif %}
		                                           {% endfor %}
		                                    </select>
										</div>	
																																														
										<div id="custom_server" class="form-group"  {% if script.script_type != 'custom' %}style="display:none;"{% endif %}>
											<label>服务器选择</label>
		                                       <select multiple class="selectpicker" data-live-search="true" name="ansible_server"  id="ansible_server" required>
		                                            {% for ds in serverList %}
		                                            	{% if ds.count  %}
		                                            		<option name="server" value="{{ds.id}}" selected="selected">{{ds.ip}} | {{ds.project}} | {{ds.service}}</option>
		                                            	{% else %}
		                                            		<option name="server" value="{{ds.id}}">{{ds.ip}} | {{ds.project}} | {{ds.service}}</option>
		                                            	{% endif %}
		                                            {% endfor %}
		                                       </select>
										</div>         
										<div class="form-group" >			 		             
											<label >语言类型: </label>	
											<div class="btn-group btn-group-sm">
												<button type="button" class="btn btn-default" onclick="setAceEditMode('sh')"><a>Shell</a></button>
												<button type="button" class="btn btn-default" onclick="setAceEditMode('python')"><a>Python</a></button>
												<button type="button" class="btn btn-default" onclick="setAceEditMode('perl')"><a>Perl</a></button>
											</div>
										</div>                                                                 
										<div id="compile-editor" class="ace_editor">{{script.script_contents}}</div> 
										<br>   
                                        <div class="form-group">
                                            <label>脚本参数</label>
                                            <input class="form-control" name="script_args" id="script_args" value="{{script.script_args|default:""}}" >
                                        </div>  										                       
										<div class="form-group">
											<label>Debug</label>									
											<select class="form-control" name="ansible_debug" id="ansible_debug">
												<option value="off" name="ansible_model">关闭</option>	
												<option value="on" name="ansible_model">开启</option> 	
											</select>
										</div> 											                 
		                                <input  type="hidden"   class="form-control" id="model" name="model" value="model">
		                                <input  type="hidden"   class="form-control" id="ans_uuid" name="ans_uuid" value="{{ans_uuid}}">  
                                        <button type="button" class="btn btn-default" {% if perms.OpsManage.can_edit_ansible_script %} onclick="saveAnsibleScript(this)" {% else %} disabled  {% endif %}>保存</button>
                                        <button type="button" class="btn btn-default" id="run_ansible_model" {% if perms.OpsManage.can_exec_ansible_script %} onclick="runAnsibleModel(this)" {% else %} disabled  {% endif %}>运行</button>		                                   
		                                                               	
                                </div>                            
                                <div class="col-lg-7">
                                    <legend><i class="fa  fa-paper-plane-o"></i>执行结果</legend>
									<pre>
				                        <div id="result">
				                        </div>
				                    </pre>                                      
                                <!-- /.col-lg-6 (nested) -->
                            </div>
                            <!-- /.row (nested) -->
                        </div>
                        <!-- /.panel-body -->
                    </div>
                    <!-- /.panel -->
                </div>
                <!-- /.col-lg-12 -->
            </div>
</div>
<div style="visibility:hidden"><a id="scrollToTop"></a></div>
<script type="text/javascript">

function setAceEditMode(model) {
	var editor = ace.edit("compile-editor");
	require("ace/ext/old_ie");
	var langTools = ace.require("ace/ext/language_tools");
	editor.setTheme("ace/theme/monokai");
	if (model == 'sh'){
		editor.removeLines();
		editor.insert("#!/bin/bash");
	}
	else if(model == 'python'){
		editor.removeLines();
		editor.insert("#!/usr/bin/python");
	}
	else if(model == 'perl'){
		editor.removeLines();
		editor.insert("#!/usr/bin/perl");
	}
	else{
		var model = 'sh'
	};
	editor.getSession().setMode("ace/mode/" + model);
	editor.setShowPrintMargin(false);
	{% if not perms.OpsManage.can_edit_ansible_script %}
	editor.setReadOnly(true);
	{% endif %}
	editor.setOptions({
	    enableBasicAutocompletion: true,
	    enableSnippets: true,
	    enableLiveAutocompletion: true
	}); 
			 
};

 setAceEditMode();

 function oBtAnsibleServerl(){
	   var obj = document.getElementById("server_model"); 
	   var index = obj.selectedIndex;
	   var value = obj.options[index].value; 
	   if (value=="group"){
		   document.getElementById("group_server").style.display = "";
		   document.getElementById("custom_server").style.display = "none";
		   document.getElementById("project_server").style.display = "none";
	   }
	   else if (value=="custom"){
		   document.getElementById("group_server").style.display = "none";
		   document.getElementById("custom_server").style.display = "";
		   document.getElementById("project_server").style.display = "none";
	   }
	   else if (value=="service"){
		   document.getElementById("group_server").style.display = "none";
		   document.getElementById("custom_server").style.display = "none";
		   document.getElementById("project_server").style.display = "";
	   }	   
	   else {
		   document.getElementById("group_server").style.display = "none";
		   document.getElementById("custom_server").style.display = "none"; 
		   document.getElementById("project_server").style.display = "none";
	   }	
}


	function oBtProjectSelect(){
		   $('#ansible_service').removeAttr("disabled");
		   var obj = document.getElementById("ansible_project"); 
		   var index = obj.selectedIndex;
		   var projectId = obj.options[index].value; 
		   if ( projectId > 0){	 
				$.ajax({
					dataType: "JSON",
					url:'/api/project/'+ projectId + '/', //请求地址
					type:"GET",  //提交类似
					success:function(response){
						var binlogHtml = '<select class="form-control" name="ansible_service" id="ansible_service" onchange="javascript:oBtServiceSelect();" required><option selected="selected" name="ansible_service" value="">请选择业务类型</option>'
						var selectHtml = '';
						for (var i=0; i <response["service_assets"].length; i++){
							 selectHtml += '<option name="ansible_service" value="'+ response["service_assets"][i]["id"] +'">' + response["service_assets"][i]["service_name"] + '</option>' 
						};                        
						binlogHtml =  binlogHtml + selectHtml + '</select>';
						document.getElementById("ansible_service").innerHTML= binlogHtml;	
							
					},
				});	
		   }
		   else{
			   $('#ansible_service').attr("disabled",true);
		   }
	
	}
	
	function oBtServiceSelect(model,ids){
		   var obj = document.getElementById(ids); 
		   var index = obj.selectedIndex;
		   var sId = obj.options[index].value; 
		   if ( sId  > 0){	 
				$.ajax({
					dataType: "JSON",
					url:'/assets_server/', //请求地址
					type:"POST",  //提交类似
					data:{
						"query":model,
						"id":sId
					},
					success:function(response){
						var sHtml = '';
						for (var i=0; i <response["data"].length; i++){
							sHtml +=  '<br>' + response["data"][i]["ip"] + " | " + response["data"][i]["project"] + " | " + response["data"][i]["service"]
						};  
						if ( sHtml.length > 0){
							$.notify({
								title: "<strong>发现主机:</strong>",
								message: sHtml
							},
							{
								type: 'info'
							});	
							$('#run_ansible_model').removeAttr("disabled");
						}
						else {
							$.notify({
								title: "<strong>Ops：</strong>",
								message: "该条件下未发现主机资源~"
							},
							{
								type: 'danger'
							});
							$('#run_ansible_model').attr("disabled",true);
						}
					
							
					},
				});	
		   }
		   else{
			   $('#server option:selected').empty();
			   $('#server').attr("disabled",true);
		   }
	
	}

	{% if perms.OpsManage.can_exec_ansible_script %}
	function runAnsibleModel(obj) {
		var btnObj = $(obj);
		btnObj.attr('disabled',true);
		var form = document.getElementById('ansibleModelRun');
		var editor = ace.edit("compile-editor");
	    var contents = editor.getSession().getValue(); 
	    if ( contents.length == 0){
	    	window.wxc.xcConfirm("脚本内容不能为空", window.wxc.xcConfirm.typeEnum.error);
	    	btnObj.removeAttr('disabled');
	    	return false;
	    };		
		$("#result").html("服务器正在处理，请稍等。。。");
		var ansible_server = new Array();
		$("#ansible_server option:selected").each(function(){
			ansible_server.push($(this).val());
        });
		/* 轮训获取结果 开始  */
 	   var interval = setInterval(function(){  
	        $.ajax({  
	            url : '/apps/run/',  
	            type : 'post', 
	            data:$('#ansibleModelRun').serialize(),
	            success : function(result){
	            	if (result["msg"] !== null ){
	            		$("#result").append("<p>"+result["msg"]+"</p>"); 
	            		document.getElementById("scrollToTop").scrollIntoView(); 
	            		if (result["msg"].indexOf("[Done]") == 0){
	            			clearInterval(interval);
	            			window.wxc.xcConfirm("Ansible执行完成", window.wxc.xcConfirm.typeEnum.success);
	            			btnObj.removeAttr('disabled');
	            		}
	            	}
	            },
		    	error:function(response){
		    		btnObj.removeAttr('disabled');
		    		clearInterval(interval);
		    	}	            
	        });  
	    },1000);  

// 	    /* 轮训获取结果结束  */
		$.ajax({
			url:'/apps/script/online/', //请求地址
			type:"POST",  //提交类似
			data:{
				'type':'run',
				'script_name':document.getElementById("script_name").value,
				'server_model':$('#server_model option:selected').val(),
				'script_args':document.getElementById("script_args").value,
				'ansible_service':$('#ansible_service option:selected').val(),
				'ansible_group':$('#script_auth_group option:selected').val(),
				'model':document.getElementById("model").value,
				'ans_uuid':document.getElementById("ans_uuid").value,
				'script_file':contents,
				'ansible_debug':document.getElementById("ansible_debug").value,
				'ansible_server':ansible_server
			},//$('#ansibleModelRun').serialize() + '&script_file=' + contents,  //不能是被脚本里面的&&符号
			success:function(response){
				btnObj.removeAttr('disabled');
				if (response["code"] == "500"){
					clearInterval(interval);
					btnObj.removeAttr('disabled');
					window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
				}
				
			},
	    	error:function(response){
	    		btnObj.removeAttr('disabled');
	    		window.wxc.xcConfirm("运行失败", window.wxc.xcConfirm.typeEnum.error);
	    		clearInterval(interval);
	    	}
		})	
	}	
	{% endif %}
	{% if  perms.OpsManage.can_edit_ansible_script %}
	function saveAnsibleScript(obj){
		var btnObj = $(obj);
		btnObj.attr('disabled',true);
		var form = document.getElementById('ansibleModelRun');
		var editor = ace.edit("compile-editor");
	    var contents = editor.getSession().getValue(); 
	    var script_name = document.getElementById("script_name").value;
	    if ( contents.length == 0 || script_name.length == 0){
	    	window.wxc.xcConfirm("脚本内容与名称不能为空", window.wxc.xcConfirm.typeEnum.error);
	    	btnObj.removeAttr('disabled');
	    	return false;
	    };		
		var ansible_server = new Array();
		$("#ansible_server option:selected").each(function(){
			ansible_server.push($(this).val());
        });
		$.ajax({
			url:'/apps/script/run/{{script.id}}/', //请求地址
			type:"POST",  //提交类似
			data:{
				'type':'save',
				'script_name':document.getElementById("script_name").value,
				'server_model':$('#server_model option:selected').val(),
				'ansible_service':$('#ansible_service option:selected').val(),
				'ansible_group':$('#script_auth_group option:selected').val(),
				'script_args':document.getElementById("script_args").value,
				'model':document.getElementById("model").value,
				'ans_uuid':document.getElementById("ans_uuid").value,
				'script_file':contents,
				'ansible_debug':document.getElementById("ansible_debug").value,
				'ansible_server':ansible_server
			},//$('#ansibleModelRun').serialize() + '&script_file=' + contents,  //不能是被脚本里面的&&符号
			success:function(response){
				btnObj.removeAttr('disabled');
				if (response["code"] == "500"){
					window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
				}
				else{
					window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.success);					
				}
				
			},
	    	error:function(response){
	    		btnObj.removeAttr('disabled');
	    		window.wxc.xcConfirm("运行失败", window.wxc.xcConfirm.typeEnum.error);
	    	}
		})			
	}
	{% endif %}
{% if errorInfo %}
	window.wxc.xcConfirm("{{errorInfo}}", window.wxc.xcConfirm.typeEnum.error);
{% endif %}
</script>

{% endblock %}